package com.king.base.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Spur
 * @date 2019/9/18
 */
public class PDFUtil {
    static int pageNum=1;
    static int pageChange=1;
    static Logger logger=LoggerFactory.getLogger(PDFUtil.class);
    /**
     * 生成特定PDF
     * @param destPath
     */
    public static void createQuotePDF(String destPath) {
        Document document=new Document(PageSize.A4,15,15,15,15);
        FileOutputStream out=null;
        PdfWriter writer=null;
        BaseFont bf = null;
        BaseFont bfEN=null;
        try {
            out=new FileOutputStream(destPath);
            writer=PdfWriter.getInstance(document,out);
            bf=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
            bfEN=BaseFont.createFont(BaseFont.TIMES_ROMAN,BaseFont.WINANSI,BaseFont.EMBEDDED);
            createHeaderFooter(document,writer,10,BaseColor.RED,BaseColor.YELLOW);
            document.open();
            Font font = new Font(bf);//正常字体
            Font fontBold = new Font(bf, 12, Font.BOLD);//正常加粗字体
            Font fontBig = new Font(bf, 20);//大字体
            Font fontBigBold = new Font(bf, 14, Font.BOLD);//加粗大字体
            //加入空行
            Paragraph blankRow = new Paragraph(18f, " ");
            document.add(blankRow);
            //添加主题
            Paragraph theme = new Paragraph("QINGDAO KINGKING APPLIED CHEMISTRY CO.,LTD", new Font(bfEN,14,Font.BOLD));
            theme.setAlignment(Element.ALIGN_CENTER);
            document.add(theme);

            //副标题
            Paragraph viceTheme = new Paragraph("15¬16F,T3,SIIC,No.195,Hongkong East Road,Laoshan Disctrict,Shandong,China"  , font);
            viceTheme.setAlignment(Element.ALIGN_CENTER);
            document.add(viceTheme);
            // QUOTATION SHEET
            Chunk chunk = new Chunk("QUOTATION    SHEET",fontBigBold);
            chunk.setUnderline(0.1f, -1f);
            Paragraph sheet=new Paragraph(chunk);
            sheet.setAlignment(Element.ALIGN_CENTER);
            document.add(sheet);
            //NO.
            Paragraph no=new Paragraph("NO.BJ19090001",new Font(bfEN));
            no.add(new Chunk("                                                                                                                                     "));
            no.add(new Chunk("Date.2019-02-12",new Font(bfEN)));
            document.add(no);
            //Date
//           Paragraph date=new Paragraph("Date.2019-02-12",new Font(bfEN));
//           date.setAlignment(Element.ALIGN_RIGHT);
//           document.add(date);
            //创建表格
            PdfPTable table=new PdfPTable(8);
            table.setWidthPercentage(100);
//           table.setTotalWidth(500);
            table.setTotalWidth(new float[]{150,150,80,80,80,60,60,80});
            String[] titles={"Pictures","Description","Size","Package","CMB(M³)","Price","MOQ","Remark"};
            createPdfHeaderForQuote(table,titles,"value");
            for(int i=0;i<800;i++){
                System.out.println(pageChange);
                if(pageChange!=pageNum){
                    document.add(blankRow);
                    createPdfHeaderForQuote(table,titles,"value");
                    pageChange=pageNum;
                }
                table.addCell("cell"+i);
            }
            document.add(table);
            //Email
            Paragraph email=new Paragraph("Email:tianyongzhi@chinaking.com",new Font(bfEN,14));
            email.getFont().setColor(BaseColor.YELLOW);
            document.add(email);
            //Tel
            Paragraph tel=new Paragraph("Tel:121212121112",new Font(bfEN,14));
            tel.getFont().setColor(BaseColor.YELLOW);
            document.add(tel);
            //Attn
            Paragraph attn=new Paragraph("Attn:cherry",new Font(bfEN,14));
            attn.getFont().setColor(BaseColor.YELLOW);
            document.add(attn);
            document.close();
        }catch (Exception e){
            e.printStackTrace();
        }



    }

    /**
     * 设置页眉页脚
     * @throws FileNotFoundException
     * @throws DocumentException
     */
    public static void createHeaderFooter(Document document,PdfWriter writer,float fontSize,BaseColor headColor,BaseColor footerColor) throws Exception{
        // step 2: Set page event
        writer.setPageEvent(new PdfPageEventHelper(){
            public void onEndPage(PdfWriter writer, Document document) {
                PdfContentByte cb = writer.getDirectContent();
                cb.saveState();

                cb.beginText();
                BaseFont bf = null;
                try {
                    bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                cb.setFontAndSize(bf, fontSize);
                cb.setColorFill(headColor);
                //Header
                float x = document.top(10);

                //左
                cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Kingking®", document.left(), x, 0);
                //右
                cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "Kingking®", document.right(), x, 0);

                //Footer
                float y = document.bottom(20);
                cb.setColorFill(footerColor);
                //左
                //cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "F-Left", document.left(), y, 0);
                //中
                cb.showTextAligned(PdfContentByte.ALIGN_CENTER,writer.getPageNumber()+" page",(document.right() + document.left())/2, y, 0);
                //右
                //cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "F-Right", document.right(), y, 0);
                pageNum=writer.getCurrentPageNumber();
                cb.endText();
                cb.restoreState();
            }
        });
    }
    /**
     * 格式不同自定义
     * @param table 生成表头
     * @param headers
     */
    public static void createPdfHeaderForQuote(PdfPTable table,String[] headers,String value){
        int rowSpan=1;
        int colSpan=0;
        for(int i=0;i<headers.length;i++){
            if(i<5){
                rowSpan=2;
            }else{
                rowSpan=1;
            }
            table.addCell(createPdfPCell(headers[i],rowSpan,colSpan,new BaseColor(16,165,202),BaseColor.YELLOW,0));
        }
        PdfPCell cell =createPdfPCell("AAA",1,3,new BaseColor(16,165,202),BaseColor.YELLOW,0);
        table.addCell(cell);
    }
    /**
     * 创建表格
     * @param head 表头或者属性值
     * @param rowSpan 跨行数
     * @param colSpan 跨列数
     * @param baseColor 背景色
     * @param fontColor 字体颜色
     * @return
     */
    public static PdfPCell createPdfPCell(String head,int rowSpan,int colSpan,BaseColor baseColor,BaseColor fontColor,float height){
        Paragraph paragraph=new Paragraph(head);
        if(fontColor !=null){
            paragraph.getFont().setColor(fontColor);
        }
        PdfPCell cell=new PdfPCell(paragraph);
        cell.setRowspan(rowSpan); //设置合并行数
        cell.setColspan(colSpan); //设置合并列数
        cell.setBackgroundColor(baseColor);
        if(height>0){
            cell.setFixedHeight(height);
        }
//        cell.setBorderColor(BaseColor.BLUE); //设置单元格边框颜色
//        cell.setPadding(10f); //单元格内部偏移量
//        cell.setFixedHeight(20f); //单元格高度
        cell.setHorizontalAlignment(Element.ALIGN_CENTER); //居中对齐
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中
        return cell;
    }
    /**
     * 根据模板生成PDF
     * @param headers 表头列名
     * @param data 模板传输值
     * @param templatePath 模板路径
     * @param destPath 文件输出路径  oss另行定义
     * @param isCreateTable 是否创建Table
     * @param  module 功能模块
     * @throws IOException
     * @throws DocumentException
     */
    public static void createPDFByTemplate(String templatePath,String destPath,Map<String,Object> data,String[] headers,boolean isCreateTable,String module)throws IOException, DocumentException{
        //读取PDF模板
        PdfReader reader=new PdfReader(templatePath);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        /* 将要生成的目标PDF文件名称 */
        PdfStamper ps = new PdfStamper(reader, bos);
        PdfContentByte under = ps.getUnderContent(1);
        /* 使用中文字体 */
        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
        ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
        fontList.add(bf);
        /* 取出报表模板中的所有字段 */
        AcroFields fields = ps.getAcroFields();
        fields.setSubstitutionFonts(fontList);
        fillData(fields, data);
        /* 必须要调用这个，否则文档不会生成的 */
        ps.setFormFlattening(true);
        if(isCreateTable){
            PdfPTable table = new PdfPTable(headers.length);
            table.setSplitLate(false);
            table.setSplitRows(true);
            table.setWidthPercentage(100);
            table.setTotalWidth(560f);
            if(module.equals("quote")){
                createPdfHeaderForQuote(table,headers,data.get("value").toString());
            }
//            for(int i=0;i<800;i++){
//                table.addCell(createPdfPCell("cell"+i,1,1,BaseColor.WHITE,100));
//            }
            table.writeSelectedRows(0,-1,10f,708f,under);
        }
        ps.close();
        File file=new File(destPath);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        file.createNewFile();
        OutputStream fos = new FileOutputStream(file);
        Document doc=new Document(PageSize.A4, 25, 25, 20, 38);
        PdfCopy copy = new PdfCopy(doc, fos);
        PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
        copy.addPage(importPage);
        doc.open();
        fos.flush();
        fos.close();
        bos.close();
        doc.close();
    }
    /**
     * 模板赋值
     * @param fields
     * @param data
     * @throws IOException
     * @throws DocumentException
     */
    public static void fillData(AcroFields fields, Map<String, Object> data)
            throws IOException, DocumentException {
        for (String key : data.keySet()) {
            String value = data.get(key).toString();
            fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
        }
    }
    public static void imgToPDF(List<String> imgUrls, String destPath) {
        logger.info("进入图片合成PDF工具方法");

        try {
            File file = new File(destPath);
            if(!file.exists()){
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            // 第一步：创建一个document对象。
            Document document = new Document(PageSize.A4,15,15,15,15);
            // 第二步：
            // 创建一个PdfWriter实例，
            PdfWriter.getInstance(document, new FileOutputStream(file)).setCompressionLevel(9);
            // 第三步：打开文档。
            document.open();

            for (String imgUrl:imgUrls) {
                if (imgUrl.endsWith(".bmp")
                        || imgUrl.endsWith(".jpg")
                        || imgUrl.endsWith(".jpeg")
                        || imgUrl.endsWith(".gif")
                        || imgUrl.endsWith(".png")) {
                    logger.info("图片路径："+imgUrl);
                    Image img = Image.getInstance(imgUrl);
                    img.setAlignment(Image.ALIGN_CENTER);
                    img.scaleAbsolute(597, 844);// 直接设定显示尺寸
                    // 根据图片大小设置页面，一定要先设置页面，再newPage（），否则无效
                    //document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
                    document.setPageSize(new Rectangle(597, 844));
                    document.newPage();
                    document.add(img);
                }
            }
            // 第五步：关闭文档。
            document.close();
            logger.info("图片合成PDF完成");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
//    public static void main(String[] args) {
//        Map<String, Object> data = new HashMap<String, Object>();
//        data.put("no", "BJ19090020");
//        data.put("date", "2019-02-12");
//        data.put("value","FOB QINGDAO,CHINA");
//        String templatePath="C:\\Users\\56398\\Desktop\\quote.pdf";
//        String destPath="d:\\1\\2\\qq.pdf";
//        data.put("email","tianyongzhi@chinakingking.com");
//        data.put("tel","0086 532 8257 8989-123");
//        data.put("attn","chris");
//        String[] titles={"Pictures","Description","Size","Package","CMB(M³)","Price","MOQ","Remark"};
////        PDFUtil.createPDF( data,templatePath);
//        try {
//            createPDFByTemplate(templatePath,destPath,data,titles,true,"quote");
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        System.out.println(String.valueOf(LocalDate.now().getMonthValue()));
//    }
}
